package com.sh.test;

import com.sh.promise.IPromise;
import com.sh.promise.Promise;

import java.util.HashMap;
import java.util.Map;

/** 测试 all
 * @Date 16:20 2023/3/10
 **/
public class Demo06 {
    public static void main(String[] args) {
        //test1();
        test2();
    }

    /**all测试某个promise发生异常,取消线程*/
    public static void test1(){
        Map<String,Boolean> p1Flag = new HashMap<>();
        p1Flag.put("flag",true);
        IPromise p1 = new Promise.Builder().externalInput(p1Flag).promiseHandler(executor -> {
            if (((Map<String,Boolean>)executor.getExternalInput()).get("flag")){
                //do something
                System.out.println("p1 正在执行任务");
            }
            System.out.println("p1任务完成，正常结束");
            return 1;
        }).build();
        IPromise p2 = new Promise.Builder().promiseHandler(executor -> {
            if (!Thread.currentThread().isInterrupted()){
                System.out.println("执行p2正常逻辑");
            }
            System.err.println("p2线程被取消");
            return 2;
        }).build();
        IPromise p3 = new Promise.Builder().promiseHandler(executor -> {
            Thread.sleep(10);
            throw new RuntimeException("p3抛出异常");
        }).build();
        IPromise p4 = new Promise.Builder().finalPromise("4",true).build();
        long s = System.currentTimeMillis();
        Promise.all(p1,p2,p3,p4).then(resolvedData -> {
            Object[] datas = (Object[])resolvedData;
            for(Object d:datas){
                System.out.println(d);
            }
            return null;
        },e->e.printStackTrace());
        System.out.println("耗时："+(System.currentTimeMillis()-s));
        p1Flag.put("flag",false);
    }
    /**测试all*/
    public static void test2(){
        IPromise p1 = new Promise.Builder().promiseHandler(executor -> {
            Thread.sleep(1000);
            return 1;
        }).build();
        IPromise p2 = new Promise.Builder().promiseHandler(executor -> {
            Thread.sleep(4000);
            return 2;
        }).build();
        IPromise p3 = new Promise.Builder().promiseHandler(executor -> {
            Thread.sleep(2000);
            return 3;
        }).build();
        long s = System.currentTimeMillis();
        Promise.all(p1,p2,p3).then(resolvedData -> {
            Object[] datas = (Object[])resolvedData;
            for(Object d:datas){
                System.out.println(d);
            }
            return null;
        },e->e.printStackTrace());
        System.out.println("耗时："+(System.currentTimeMillis()-s));
    }
}
